#!/bin/bash
#   -x
set -e
set -u

function fix_reslv_zone() {
    
    local _RESOLV_CONV
    local LINE
    local indexa
    local indexb
    local part
    local zone
    local forwards
    declare -a LINES
    declare -a DOMAIN_ARR
    
    indexa=0
    _RESOLV_CONV="/etc/resolv.conf"
    
    
    while read LINE
    do
    
        if [[ "${LINE}" =~ ^#.* ]];
        then
            echo ""
        else
    
        if [[ "${LINE}" =~ ^search.* ]];
        then
            DOMAIN_ARR=( `echo ${LINE} `)
        fi
        
        if [[ "${LINE}" =~ ^nameserver.* ]];
        then
            part=`echo ${LINE} |cut -d ' ' -f2`
            NAMESERVER_ARR[${indexa}]=${part}
            let "indexa=$indexa+1"
        fi
    fi
    done < ${_RESOLV_CONV}
    unset DOMAIN_ARR[0]
    
    indexa=""
    indexb=""
    zone=""
    
    for indexa in ${DOMAIN_ARR[*]} 
    do
        indexb=""
        forwards=""
        for indexb in ${NAMESERVER_ARR[*]} 
        do
        forwards="${forwards}\n\t\t${indexb};"
        done
    
    zone="${zone}\nzone \"${indexa}\" {
\ttype forward;
\tforwarders {
\t${forwards}
\t};
};"    
    done
    
    #echo -e  "$zone"
    can_add="true"
    
    for iii in ${DOMAIN_ARR[*]}
    do
    cat /tmp/zones | grep -q $iii && can_add="false"
    done 
    
    if [ "$can_add" == "true" ]
    then 
    echo "adddind NEW zone ${DOMAIN_ARR[*]} to DNS"
    else
    echo "Zone  ${DOMAIN_ARR[*]} exsist in  DNS"
    fi
    
    #echo "LINES:: ${LINES[*]}"
    #echo "DOMAIN_ARR:: ${DOMAIN_ARR[*]}"
    #echo "${DOMAIN_ARR[*]}"
    #echo "NAMESERVER_ARR:: ${NAMESERVER_ARR[@]}"
    

}



function main() {
    fix_reslv_zone
    }

main
